package com.winapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.winapi.project.common.BaseResponse;
import com.winapi.project.common.ResultUtils;
import com.winapi.project.model.dto.orders.OrderQueryRequest;
import com.winapi.project.model.dto.orders.OrdersAddRequest;
import com.winapi.project.model.vo.OrderVO;
import com.winapi.project.service.OrderService;
import com.winapi.winapicommon.model.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yyzhang
 * @version 1.0
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {
    private static final String orderLog="订单模块-";
    @Resource
    private OrderService orderService;

    /**
     * 根据类型来查询接口列表
     * @param orderQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<Page<OrderVO>> listPageOrder(OrderQueryRequest orderQueryRequest, HttpServletRequest request){
        log.info(orderLog+"根据类型查询订单列表-进入接口......");
        long current = 1;
        long size = 10;
        Orders orderQuery = new Orders();
        if (orderQueryRequest != null) {
            BeanUtils.copyProperties(orderQueryRequest, orderQuery);
            current = orderQueryRequest.getCurrent();
            size = orderQueryRequest.getPageSize();
        }
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>(orderQuery);
        Page<Orders> orderPage = orderService.page(new Page<>(current, size), queryWrapper);
        log.info(orderLog+"根据类型查询订单列表-在业务层按分页查询");
        Page<OrderVO> orderVOPage = new PageDTO<>(orderPage.getCurrent(), orderPage.getSize(), orderPage.getTotal());
        List<OrderVO> orderVOList = orderPage.getRecords().stream().map(order -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            Integer number = order.getNumber();
            Double price = order.getPrice();
            orderVO.setTotalAmount(number*price);
            return orderVO;
        }).collect(Collectors.toList());
        orderVOPage.setRecords(orderVOList);
        log.info(orderLog+"根据类型查询订单列表-结束接口......");
        return ResultUtils.success(orderVOPage);
    }

    @PostMapping("/addOrder")
    public BaseResponse<OrderVO> addOrder(@RequestBody OrdersAddRequest ordersAddRequest,HttpServletRequest request){
        log.info(orderLog+"创建新的订单-进入接口......");
        OrderVO order = orderService.addOrder(ordersAddRequest,request);
        log.info(orderLog+"创建新的订单-结束接口......");
        return ResultUtils.success(order);
    }
}
